/**
 * 
 */
package de.mbenning.fsim.web.servlet;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ResourceBundle;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Martin.Benning
 *
 */
public class FsimResourcesServlet extends HttpServlet {

	private static final long serialVersionUID = -6479879278498380163L;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String uploadDir = ResourceBundle.getBundle("fsim-webeditor").getString("fsim.webeditor.uploaddir");
		String resourceId = request.getParameter("resourceid");
		if(resourceId != null && !resourceId.equalsIgnoreCase("")) {
	        File                f        = new File(uploadDir + "/" + resourceId);
	        int                 length   = 0;
	        ServletOutputStream op       = response.getOutputStream();
	        ServletContext      context  = getServletConfig().getServletContext();
	        String              mimetype = context.getMimeType( resourceId );

	        response.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
	        response.setContentLength( (int)f.length() );
	        response.setHeader( "Content-Disposition", "attachment; filename=\"" + resourceId + "\"" );
	       
	        byte[] bbuf = new byte[1024];
	        DataInputStream in = new DataInputStream(new FileInputStream(f));

	        while ((in != null) && ((length = in.read(bbuf)) != -1))
	        {
	            op.write(bbuf,0,length);
	        }

	        in.close();
	        op.flush();
	        op.close();
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
